/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tcloudclient.traySupport;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.TrayIcon.MessageType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;

/**
 *
 * @author Tomas
 */
public class TraySupport {

    private TrayIcon trayIcon;
    private boolean supported;
    private TraySupportWatchServiceObserver watchServiceObserver;
    private JFrame main;

    public TraySupport(JFrame main) {
        supported = SystemTray.isSupported();
        if (supported) {
            initTray();
            this.main = main;
        }
        watchServiceObserver = new TraySupportWatchServiceObserver(this);
    }

    private void initTray(){
        SystemTray systemTray = SystemTray.getSystemTray();
       
        Image image = Toolkit.getDefaultToolkit().getImage("./images/icon.png");

        ActionListener exitListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        };

        PopupMenu popup = new PopupMenu();
        MenuItem defaultItem = new MenuItem("Exit");
        defaultItem.addActionListener(exitListener);
        popup.add(defaultItem);
        
        trayIcon = new TrayIcon(image, "tCloud", popup);
        
        trayIcon.setImageAutoSize(true);
        trayIcon.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                main.setVisible(true);
            }
        });
        try {
            systemTray.add(trayIcon);
        } catch (AWTException ex) {
            Logger.getLogger(TraySupport.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void displayMessage(String caption, String message, MessageType messageType){
        trayIcon.displayMessage(caption, message, messageType);
    }

    public TraySupportWatchServiceObserver getWatchServiceObserver() {
        return watchServiceObserver;
    }
}
